import subprocess
import time

import yaml
import os
import concurrent.futures
import threading
import uiautomator2 as u2
from apkutils2.axml.public import resources


def run_adb_command(command):
    try:
        # 使用 check_output 来执行 ADB 命令
        output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True, text=True)
        return output
    except subprocess.CalledProcessError as e:
        # 如果命令执行失败，返回错误信息
        return e.output

def read_config_from_yaml():
    # 获取当前脚本所在的目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    # 构建文件路径
    file_path = os.path.join(script_dir, 'config', 'config.yml')

    print(f"尝试读取文件: {file_path}")  # 调试输出

    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return yaml.safe_load(file)
    except FileNotFoundError:
        print(f"文件未找到: {file_path}")
    except PermissionError:
        print(f"没有权限读取文件: {file_path}")
    except yaml.YAMLError as e:
        print(f"YAML 解析错误: {e}")
    except Exception as e:
        print(f"未知错误: {e}")

def auto_send_message(device_serial, config):
    # 连接设备
    device = u2.connect(device_serial)
    device.app_stop("com.ss.android.ugc.aweme")
    # 启动抖音
    device.session("com.ss.android.ugc.aweme", attach=True)
    print(f"正在操作设备: {device_serial}")
    # 点击消息按钮
    msg_view = device(text="消息")
    if msg_view.exists(timeout=30):
        print("正在点击消息按钮")
        time.sleep(3)
        msg_view.click()
    else:
        print("消息按钮未找到")
        return
    # 点击搜索框
    search_view = device(resourceId="com.ss.android.ugc.aweme:id/kcn")
    if search_view.exists(timeout=30):
        print("正在点击搜索框")
        time.sleep(3)
        search_view.click()
    else:
        print("搜索框未找到")
        return
    # 搜索群名
    device(resourceId="com.ss.android.ugc.aweme:id/et_search_kw").send_keys(config['group_name'])
    # 点击打开群聊
    group_view =  device(text="群聊").sibling(resourceId="com.ss.android.ugc.aweme:id/content_container")
    if group_view.exists(timeout=30):
        group_view.click()
        print("打开群聊成功")
    else:
        print("群聊未找到")
        return
    send_msg_view = device(resourceId="com.ss.android.ugc.aweme:id/msg_et")
    while True:
        if send_msg_view.exists(timeout=30):
            print("正在发送消息")
            send_msg_view.send_keys(config['msg'])
            time.sleep(3)
            device(resourceId="com.ss.android.ugc.aweme:id/jgb").click()
        time.sleep(config['interval'])

def main():
    # ADB 命令，这里列出所有已连接的设备
    command = "adb devices"
    # 执行 ADB 命令
    device_list = run_adb_command(command).splitlines()[1:]
    if len(device_list) == 0 or (len(device_list) == 1 and device_list[0].strip() == ""):
        print("没有设备连接")
        return
    # 读取配置文件
    config = read_config_from_yaml()
    print(config)
    with concurrent.futures.ThreadPoolExecutor() as executor:
        futures = []

        for device in device_list:
            if device.strip() == "":
                continue
            device_serial = device.strip().split("\t")[0]
            device_state = device.strip().split("\t")[1]
            print(device_serial, device_state)
            if device_state != "device":
                print(f"{device_serial} 设备未连接")
                continue
            # 提交任务到线程池
            future = executor.submit(auto_send_message, device_serial, config)
            futures.append(future)

        # 等待所有任务完成
        concurrent.futures.wait(futures)

if __name__ == '__main__':
    main()